package com.itheima.task;

import com.itheima.common.constant.RedisConstant;
import com.itheima.common.utils.AliOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.stereotype.Component;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.Set;


@Component
@Slf4j
public class PictureTask {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private AliOssUtil aliOssUtil;
    /**
     * 处理阿里云oss中的垃圾图片
     */
    @Scheduled(cron="0 0 0 * * ? ")//每日零点执行
    public void deletePicture(){
        log.info("删除阿里云中垃圾图片定时任务开始执行......");
        //根据Redis中保存的两个set集合进行差值计算，获得垃圾图片名称集合
        Set<String> set= redisTemplate.opsForSet().difference(RedisConstant.SETMEAL_PIC_RESOURCES,RedisConstant.SETMEAL_PIC_DB_RESOURCES);
        /*SetOperations set = redisTemplate.opsForSet();
        Set<String> differenceSet = set.difference(RedisConstant.SETMEAL_PIC_RESOURCES,
                RedisConstant.SETMEAL_PIC_DB_RESOURCES);*/
        log.info("垃圾图片名称集合大小：{}",set.size());
        if(set != null && set.size() > 0){
            for (String picName : set) {
                //从Redis集合中删除图片名称
                redisTemplate.opsForSet().remove(RedisConstant.SETMEAL_PIC_RESOURCES,picName);
                //删除阿里云服务器上的图片
                String objectName=picName.split("/")[4];
                log.info("删除文件:{}", objectName);
                aliOssUtil.delete(objectName);

            }
        }
        else{
            log.info("没有垃圾图片需要删除");
        }
        log.info("删除阿里云中垃圾图片定时任务执行完毕......");
    }
}
